package com.zxl.gtion.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Charsets;
import com.zxl.gtion.enums.RedisEnums;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Author: bo-feifei
 * @Date 2024/3/11 17:31
 * @Version 1.0
 */
@Component
public class BaiDuUtil {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${baidu.wenxin.apiKey}")
    private String apiKey;
    @Value("${baidu.wenxin.secretKey}")
    private String secretKey;

    public String getAccessToken() {
        String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + apiKey
                + "&client_secret=" + secretKey;
        HttpResponse response = HttpRequest.post(url)
                .timeout(5000)
                .charset(Charsets.UTF_8)
                .method(Method.POST)
                .header("Content-type", "application/json")
                .execute();
        if (response.getStatus() == 200) {
            String body = response.body();
            JSONObject jsonObject = JSON.parseObject(body);

            if (jsonObject.get("error") != null) {
                return "获取accessToken报错，报错信息：" + jsonObject.get("error_description");
            }
            return jsonObject.get("access_token").toString();
        }
        return null;
    }
}
